<template>
  <div id="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="input-header">
          <el-input
            placeholder="请输入内容"
            v-model="questList.query"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </div>
        <el-button class="addBtn" type="primary" @click="dialogVisible = true"
          >添加按钮</el-button
        >
        <!-- 弹出对话框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="dialogVisible"
          @close="dialogDown"
          width="50%"
        >
          <el-form
            :model="addUsers"
            :rules="addRules"
            ref="addRef"
            label-width="70px"
            status-icon
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUsers.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addUsers.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUsers.email" type="email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="addUsers.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="detail()">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <div>
        <el-table :data="userList.users" style="width: 100%" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                @change="changeSwitch(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="editor(scope.row)"
              >
              </el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="delOpen(scope.row.id)"
              ></el-button>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配权限"
                :enterable="false"
                placement="top"
              >
                <el-button
                  type="warning"
                  @click="darkInfo(scope.row)"
                  icon="el-icon-setting"
                ></el-button>
              </el-tooltip>
              <!-- 操作编辑对话框 -->
              <el-dialog
                title="编辑用户"
                :visible.sync="editorVisible"
                width="50%"
                @close="editorDialog"
              >
                <el-form
                  :model="editorUser"
                  :rules="editorRules"
                  ref="editorRef"
                  label-width="70px"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="editorUser.username" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editorUser.email"></el-input>
                  </el-form-item>
                  <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editorUser.mobile"></el-input>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="editorVisible = false">取 消</el-button>
                  <el-button type="primary" @click="detailEditor(editorUser.id)"
                    >确 定</el-button
                  >
                </span>
              </el-dialog>
              <!-- 分配权限对话提示框 -->
              <el-dialog
                title="分配角色"
                :visible.sync="darkVisible"
                width="50%"
                @close="resetJs"
              >
                <p>当前用户：{{ darkUserInfo.username }}</p>
                <p>当前角色：{{ darkUserInfo.role_name }}</p>
                <p>分配新角色：
                <el-select v-model="selectID" placeholder="请选择">
                  <el-option
                    v-for="item in allUserInfo"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                </p>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="darkVisible = false">取 消</el-button>
                  <el-button type="primary" @click="setEditorVisible"
                    >确 定</el-button
                  >
                </span>
              </el-dialog>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="questList.pagenum"
          :page-sizes="[1, 4, 10, 20]"
          :page-size="questList.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'users',
  data() {
    // 密码验证
    const checkPassword = (rule, value, cb) => {
      let reg = /^[a-zA-Z0-9_.-]{3,10}$/
      if (reg.test(value)) {
        cb()
      } else {
        return cb(new Error('密码格式不正确'))
      }
    }
    // 邮箱格式验证
    const checkEmail = (rule, value, cb) => {
      let reg =
        /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9_\.\-])+\.)+([a-zA-Z0-9]{2,4})+$/
      if (reg.test(value)) {
        return cb()
      } else {
        return cb(new Error('邮箱格式不正确'))
      }
    }
    // 手机号格式验证
    const checkMobile = (rule, value, cb) => {
      let reg =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机号码格式不正确'))
      }
    }

    return {
      // 获取数据
      questList: {
        // 查询参数
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 3,
      },
      userList: [],
      total: 0,
      value: false,
      dialogVisible: false,
      editorVisible: false,
      delVisible: false,
      darkVisible: false,
      // 添加用户
      addUsers: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加表单验证
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 之间', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 编辑用户
      editorUser: {
        id: '',
        email: '',
        mobile: '',
        role_id: '',
      },
      // 编辑表单验证
      editorRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 分配权限
      darkUserInfo: {},
      // 获取所有的角色列表
      allUserInfo: [],
      // 已选中新角色
      selectID:'',
    }
  },
  created() {
    this.getUsers()
  },
  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get('users', {
        params: this.questList,
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data
      this.total = res.data.total //总数据
      // console.log(this.userList)
    },
    // 每页几条
    handleSizeChange(newPage) {
      // console.log(newPage)
      this.questList.pagesize = newPage
      this.getUsers()
    },
    // 当前第几页
    handleCurrentChange(newNum) {
      // console.log(newNum)
      this.questList.pagenum = newNum
      this.getUsers()
    },
    // 修改用户的状态
    async changeSwitch(getList) {
      const { data: res } = await this.$http.put(
        `users/${getList.id}/state/${getList.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 整体添加表单验证
    detail() {
      this.$refs.addRef.validate(async (vail) => {
        if (vail == false) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.post('users', this.addUsers)
        this.$message.success('添加成功')
        this.getUsers()
        this.dialogVisible = false
      })
    },
    // 关闭对话框时触发
    dialogDown() {
      this.$refs.addRef.resetFields()
    },
    // 编辑信息
    async editor(editorUser) {
      const { data: res } = await this.$http.get(`users/${editorUser.id}`)
      this.editorVisible = true
      if (res.meta.status !== 200)
        return this.$message.error('获取用户信息失败')
      this.editorUser = res.data
      console.log(this.editorUser)
    },
    // 点击确定编辑
    detailEditor(id) {
      this.$refs.editorRef.validate(async (vail) => {
        if (vail == false) return this.$message.error('表单验证失败')
        const { data: res } = await this.$http.put(
          `users/${id}`,
          this.editorUser
        )
        this.$message.success('信息编辑成功')
        this.editorVisible = false
        this.getUsers()
        console.log(res)
      })
    },
    // 关闭编辑对话框
    editorDialog() {
      this.$refs.editorRef.resetFields()
    },
    // 删除用户
    delOpen(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          this.$message.success('删除成功!')
          this.getUsers()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 分配权限
    async darkInfo(darkUser) {
      this.darkUserInfo = darkUser
      this.darkVisible = true
      // 获取所有的角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.allUserInfo = res.data
      // console.log(res.data)
    },
    // 点击确定分配角色
    async setEditorVisible(){
      if(!this.selectID){
        return this.$message.error('请选择要分配的新角色')
      }
      const {data:res} = await this.$http.put(`users/${this.darkUserInfo.id}/role`,{
        rid:this.selectID
      })
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUsers();
      this.darkVisible = false
    },
    //关闭分配角色对话框
    resetJs(){
      this.selectID = '',
      this.darkUserInfo = ''
    }
  },
  
}
</script>

<style lang="less" scoped>
.box-card {
  background-color: #fff;
  margin-top: 15px;
  box-shadow: none;
}

.input-header {
  display: inline-block;
  width: 33.3%;
}
.el-table {
  font-size: 12px;
}

.el-pagination {
  margin-top: 15px;
}
/deep/.el-card__body {
  padding: 0 20px;
}
.el-button {
  padding: 7px 15px;
}
.addBtn {
  padding: 12px 20px;
  margin-left: 15px;
}
.el-dialog p{
  margin:14px 0 ;
}
/deep/ .el-card{
  box-shadow: none !important;
}

</style>